import React, { useEffect, useMemo, useRef } from "react";
import { CustomerCreditProps } from "./interface";
import { CustomerCreditItem } from "./CustomerCreditItem";
import { CustomerCreditContainer, CustomerCreditInner } from "./styles";
import { useResizeDetector } from "react-resize-detector";
import { Element, scroller } from "react-scroll";
import { nanoid } from "nanoid";
const itemMinHeight = 32;

const CustomerCredit = (props: CustomerCreditProps) => {
  const {
    count = 6,
    dataSource = [],
    duration = 1500,
    containerId = "containerElement",
  } = props;
  const containerIdMemo = useMemo(() => {
    return containerId + nanoid(4);
  }, [containerId]);

  const timerRef = useRef<any>();

  const { height = 0, ref } = useResizeDetector({
    handleWidth: false,
  });
  const itemHeight = height ? height / count : itemMinHeight;
  const curTopIndexRef = useRef(1);
  const startScroll = () => {
    clearTimeout(timerRef.current);
    timerRef.current = setTimeout(() => {
      if (curTopIndexRef.current > dataSource.length - count + 3) {
        curTopIndexRef.current = 0;
      }
      scroller.scrollTo(curTopIndexRef.current + 1 + "", {
        duration,
        smooth: true,
        containerId: containerIdMemo,
      });
      curTopIndexRef.current += 1;
      startScroll();
    }, duration);
  };
  useEffect(() => {
    if (!height || !duration) {
      return;
    }
    curTopIndexRef.current = 1;
    startScroll();
    return () => {
      clearTimeout(timerRef.current);
    };
  }, [height]);

  return (
    <CustomerCreditContainer minHeight={itemMinHeight * count} ref={ref}>
      <CustomerCreditInner id={containerIdMemo}>
        {dataSource.map((d, index) => (
          <Element name={index + 1 + ""} key={index}>
            <CustomerCreditItem
              {...props}
              {...d}
              index={index + 1}
              key={index}
              itemHeight={itemHeight}
            />
          </Element>
        ))}
      </CustomerCreditInner>
    </CustomerCreditContainer>
  );
};

export default CustomerCredit;

export * from "./CustomerCreditItem";
